﻿/* *************************************************
* 			Product Specialist Version 1.01
* 			Modified By: Brad Pipkin bpipkin@doubleclick.net
* 			Date: 10/17/2006
*  ************************************************/

class motifAdHolder extends MovieClip {
	
    ////////////////////    PRIVATE MEMBERS ////////////////////

    // private data members
    private var m_motifAdSWF:MovieClip = null;
    private var m_motifAd = null;
    private var m_motifMainAsset = null;
    private var m_sound:Sound = null;	

	//BP Added:
	private var m_thisHolderLoaded:Boolean = null;	//Flag set to true confirming initial DARTShell has been loaded.
	private var m_thisAdLoaded:Boolean = null;	//Flag set to true when ad is retuned to this holder
	public var m_playbackObjectAssigned:Boolean = null;	//Flag set to true to confirm a valid ad request can now be made.
	private var m_thisShellVersionLoaded:Number = null;
	//Roadblock specific
	private var m_rdblk_tileIndex:Number = null;	
	private var m_rdblk_tempTile:String = null;	
	private var m_rdblk_szIndex:Number = null;	
	private var m_rdblk_tempSz:String = null;	
	private var m_rdblk_masterTag:Array = null;	
	private var m_rdblk_DCSeed:String = null; 
	private var m_rdblk_DCSeed_Interval:Number = null;
	private var m_rdblk_companionTag:String = null;
	private var m_rdblk_f2Companion:Object = null;

    ////////////////////    PUBLIC MEMBERS ////////////////////	
    public var m_ns:NetStream = null;
	
    //This may be set to https if needed
    [Inspectable(defaultValue="http://")]
    public var protocol:String = "http://";

    //This may be localized outside of the US (e.g. "ad.uk.doubleclick.net")
    [Inspectable(defaultValue="ad.doubleclick.net")]
    public var host:String = "ad.doubleclick.net";

    //SWF which contains overall API. Do not change unless told to by Doubleclick: Flash Player 7 version
    [Inspectable(defaultValue="DartShellPlayer7_2_13.swf")]
    public var adswfPlayer7:String = "DartShellPlayer7_2_13.swf ";

	//SWF which contains overall API. Do not change unless told to by Doubleclick: Flash Player 8 version
    [Inspectable(defaultValue="DartShellPlayer8_2_13.swf")]
    public var adswfPlayer8:String = "DartShellPlayer8_2_13.swf ";
	
    //Complete DART ad tag passed in by designer. This is an alternative to the other ad tags parameters
    [Inspectable(defaultValue="")]
    public var adTagURL:String = "";

    //DART ad tag site parameter
    [Inspectable(defaultValue="MotifF2F")]
    public var adSite:String = "MotifF2F";

    //DART ad tag zone parameter
    [Inspectable(defaultValue="F2FTest")]
    public var adZone:String = "F2FTest";

    //DART ad tag size parameter
    [Inspectable(defaultValue="1000x1000")]
    public var adSize:String = "1000x1000";

    //DART ad tag keyval
    [Inspectable(defaultValue="")]
    public var adKeyVal:String = ""; //TODO, turn into Array
    
    //X positioning of the ad relative to the SWC
    [Inspectable(defaultValue="0")]
    public var adx:Number = 0;

    //Y positioning of the ad relative to the SWC
    [Inspectable(defaultValue="0")]
    public var ady:Number = 0;

	//Flash video player version (7 or 8)
    [Inspectable(defaultValue="8")]
    public var flashPlayer:Number = 8;

    //Set to false before publishing
    [Inspectable(defaultValue="false")]
    public var testingMode:Boolean = false;

    //Playback object for streaming video
    [Inspectable(defaultValue="")]
    public var playbackObject:Object = null;

    //Video buffer time
    [Inspectable(defaultValue=5)]
    public var videoBuffer:Number = 5;

	public var tile:String;
	public var ord:Number;
	
//-------------------------------------------------------------------------------------------
	/* ADDED BY The Chopping Block */
//-------------------------------------------------------------------------------------------	
	//is because sometimes FF runs onDartShellLoaded twice, causing it to setVideo function in controller twice, which overrides the first setVideo
	public var isInitialized:Boolean = false;
	
	//check again
	public var checkedAgain:Boolean = false;
	
	//property to refer to controller of video app
	public var controller:Object;
	
	//property for default speed
	public var speed:String;

    public function motifAdHolder() {
		trace("\t\t MOTIF motifAdHolder contstructed");
    }

//-------------------------------------------------------------------------------------------
	/* END ADDED BY The Chopping Block */
//-------------------------------------------------------------------------------------------

/*
-------------------------------------------------------------------------------------------
	These Methods have either been modified or created by 
	a Motif Product Specialist
------------------------------------------------------------------------------------------
*/

	//See above for original Engineering version of this method
    public function onLoad(Void):Void {
		trace("\t\t MOTIF onLoad")
        //Required. Change to host if outside US (e.g. uk.doubleclick.net)
        System.security.allowDomain(this.protocol + this.host);
		this.loadDartShell();
    }

	//BP: Added this to allow developer to just pass reference to the video object, and this motifAdHolder
	//will automatically determine which player version they are using.  It will reload the 8 version of the DARTShell
	//if the developer assigned an 8 component.  This approach frees the developer from indicating playbackObject and flashPlayer
	//values separately.
	public function assignVideoObject(videoPlayer:Object):Void{
		trace("\t\t MOTIF assignVideoObject")
		//this.log(this + ".motifAdHolder.assignVideoObject() on: " + videoPlayer + " and ShellVersionLoaded: " + this.m_thisShellVersionLoaded);
		if(videoPlayer.maintainAspectRatio == undefined){
			trace('\t\t --------> flashplayer 7');
			flashPlayer = 7;			
		}
		else{
			if(this.m_thisShellVersionLoaded!=8){
				//this.log(this + ".motifAdHolder.assignVideoObject(), flashPlayer was not already 8, reload 8 shell ");
				trace('\t\t --------> flashplayer 8');
				flashPlayer = 8;
				//reload player 8 version of DARTShell
				this.loadDartShell();
			}
		}
		this.playbackObject = videoPlayer;
		this.m_playbackObjectAssigned = true;
	}
	
	//BP: Moved this from onLoad into it's own to allow the reload ability if this instance 
	//is used for inStream ad call, and video object is player 8 FLVPlayback component.
	public function loadDartShell():Void{
		trace("\t\t MOTIF loadDartShell")
		//if initial load, this doesn't exist yet to hold the shell, so create it.
		if(m_motifAdSWF==null){
			//this.log("loadDartShell(). create empty clip for adshell");
			m_motifAdSWF = this.createEmptyMovieClip("motifAdSWF_mc", this.getNextHighestDepth());		
		}
		var adswf = (flashPlayer == 7) ? adswfPlayer7 : adswfPlayer8;
	
		if(adswf==7){
			this.m_thisShellVersionLoaded = 7;
		}
		if(adswf>=8){
			this.m_thisShellVersionLoaded = 8;
		}		

        //This URL is the same for all clients. It is versioned and may be updated over time
		this.m_motifAdSWF.loadMovie(this.protocol + this.host + "/879366/" + adswf);
		//this.log(this + ".motifAdHolder.onLoad(): Loading " + (this.protocol + this.host + "/879366/" + adswf) +"\n");
        //this.log(this + ".motifAdHolder.onLoad(): AdHolder loaded\n");
	}
	    
/*
-------------------------------------------------------------------------------------------
	These Methods are exactly as documented by Engineering
------------------------------------------------------------------------------------------
*/
	

    //required function, do not change
    public function allowDcDomain(strDomain:String):Void {
        System.security.allowDomain(strDomain);
    }

    //use parent logger, if defined
    public function log(logMessage:String) {
        //sent any errors to the custom error handler
        if (_level0.logEvent == undefined) 
            trace(this + ".motifAdHolder: " +logMessage);
        else 
            _level0.logEvent(logMessage);
			//TODO: Add event broadcaster here.
			trace(logMessage);
    }
    
    // onDartShellLoaded method must be present and have the following signature
    // since it will be invoked by DartShell after it has successfully initialized
    public function onDartShellLoaded(Void):Void {
		trace("\t\t MOTIF onDartShellLoaded")
        //this.log(this + ".motifAdHolder.onDartShellLoaded(): Dart Shell Loaded\n");
        // initialize reference
        m_motifAd = m_motifAdSWF.instanceName;
		
		// Best practice is to either use loadAdAsset OR split between Flash and streaming handlers, not both.

        m_motifAdSWF.addEventListener("onInStreamAdLoaded", this);
        m_motifAdSWF.addEventListener("onError", this);
		
		if(this.m_playbackObjectAssigned && !this.isInitialized) {
			this.isInitialized = true;
			
			//this.controller.setVideo();			
		}
    }

    public function loadNewAd() {
		trace("\t\t MOTIF loadNewAd");
		this.m_thisAdLoaded = false;
		//this.checkedAgain = false;

        if (m_motifMainAsset != undefined) {
            //this.log(this + ".motifAdHolder.loadNewAd(): Unload current asset\n");
            if (testingMode != true) {
                m_motifMainAsset.unLoad(); //doesn't work locally for testing because of Flash security issue
            } else {
                m_motifMainAsset.hide(); //note, this does not actually kill the ad, only for use in testing
            }
        }
        //Ad can be loaded from DART by parameters or by a URL String
        if (this.adTagURL.length > 0) {
            //String method
            log(this + ".motifAdHolder.loadNewAd(): Ad Call by string: " + adTagURL + "\n");
            m_motifAdSWF.loadAdByURL(this.adTagURL);
        } else {
            //this.log(this + ".motifAdHolder.loadNewAd(): Ad Call by parameters\n");
            //Parameter method:
            //var ord:Number = Math.floor(Math.random()*100000);
            var adcall:String = this.protocol + this.host + "/pfadx/" + this.adSite + "/" + this.adZone + ";dcmt=text/html;sz=" + this.adSize + ";kw=" + this.adKeyVal + this.tile +";ord=" + this.ord + "?";
            //this.log(this + ".motifAdHolder.loadNewAd(): adcall: "+adcall);
            this.m_motifAdSWF.loadAdByURL(adcall); //TODO fix for keyval usage
        }
		trace("\t\t END MOTIF loadNewAd");
    }

	// Function for streaming assets
	public function onInStreamAdLoaded(Void):Void {
			trace("\t\t MOTIF onInStreamAdLoaded");

	        var ad = this.m_motifAdSWF.getAd();
			trace("\t\t adID = "+ad)
			if(ad.getAdId() == null || ad.getAdId() == undefined) {
				this.controller.checkAd(false);
				return;				
			}
			//reset to check if motif video click worked.
			this.controller.motifVideoClicked = false;
			
	        //this.log("motifAdHolder.onInStreamAdLoadedAd(): Streaming ad returned\n");
			this.m_thisAdLoaded = true;

	        ad.addEventListener("onVideoClick", this);
	        ad.addEventListener("onConnect", this);

			if (flashPlayer == 7) {
				// ad.connect() only used if using video instance is Flash 7 ... don't use for FLVPlayback component
				//this.log("motifAdHolder.onInStreamAdLoadedAd(): 7 approach: ad.connect()\n");
				ad.connect();
			}
			
			trace("\t\t\t I'm a valid ad!");
			
			if (flashPlayer == 8) {
				//this.log("motifAdHolder.onInStreamAdLoadedAd(): 8 approach: ad.play(playbackObject) object: " +this.playbackObject+"\n");
				switch (this.speed) {
					case "low":
						var adBandwidth = this.m_motifAdSWF.LOW_BANDWIDTH;
					break;
					case "medium":
						var adBandwidth = this.m_motifAdSWF.MEDIUM_BANDWIDTH;				
					break;
					case "high":
						var adBandwidth = this.m_motifAdSWF.HIGH_BANDWIDTH;
					break;
					default:
						var adBandwidth = this.m_motifAdSWF.MEDIUM_BANDWIDTH;
					break;
				}
				ad.play(this.playbackObject, adBandwidth);

				//get the URL from the ad's XML
				var adData:XML = new XML(ad.getXMLNode());
				adData.ignoreWhite = true;
				this.controller.adURL = adData.childNodes[0].childNodes[1].childNodes[5].childNodes[0].nodeValue;
				//this.controller.showAdClickBox();
				//make sure autoPlay isn't on 
				this.playbackObject.autoPlay = false;
				this.controller.checkAd(true);
			}
	    }

	//	onError handler
	//	then getAdId check not null or undefined
	//user defined error handler, should be named onError
 
   public function onError(errorObj:Object) {
		trace("\t\t MOTIF onError");
        //sent any errors to the custom error handler
        this.log(this + ".motifAdHolder.onError()errObj.msg: "+errorObj.msg + "\n");
        this.log(this + ".motifAdHolder.onError()errObj.msg.shellError.getErrorType(): "+errorObj.shellError.getErrorType() + "\n");
        this.log(this + ".motifAdHolder.onError()errObj.msg.shellError.getErrorCode(): "+errorObj.shellError.getErrorCode() + "\n");
        this.log(this + ".motifAdHolder.onError()errObj.msg.shellError.getErrorMessage(): "+errorObj.shellError.getErrorMessage()+ "\n");

		if(!this.checkedAgain) {
			this.checkedAgain = true;
			loadNewAd();
		} else {
			this.checkedAgain = false;
			this.controller.checkAd(false);
		}
    }	

	//	public function 
	public function onVideoClick(Void):Void {
		trace("\t\t MOTIF onVideoClick");
		this.controller.motifVideoClicked = true;
	}
	
    public function onAssetLoad(Void):Void {
		trace("\t\t MOTIF onAssetLoad");
        // position the asset
        m_motifMainAsset.setX(this.adx);
        m_motifMainAsset.setY(this.ady); 
        m_motifMainAsset.show(); //records an impression
    }

    public function hideMainAsset(Void):Void {
		trace("\t\t MOTIF hideMainAsset");
        //this.log("AdHolderPlayer.hideMainAsset(): Hiding ad\n");
        m_motifMainAsset.hide(); //hides ad, but retains the ad in memory
    }
    
    public function moveMainAsset():Void {
		trace("\t\t MOTIF moveMainAsset");
        //this.log("AdHolderPlayer.moveMainAsset(): Moving ad\n");
        m_motifMainAsset.setX(this.adx);
        m_motifMainAsset.setY(this.ady);
    }
   
    public function onConnect(Void):Void {
        this.log(this + ".motifAdHolder.onConnect(): Received connection\n");
        var ad = m_motifAdSWF.getAd();
		if(_global.globalSound ==  undefined ||  _global.globalSound == null)
			m_sound = new Sound();
		else
			m_sound = _global.globalSound;
        m_ns = ad.getNetStream(this.playbackObject, m_sound);
        if(m_ns != null) {
			this.playbackObject.attachVideo(m_ns);
			m_ns.setBufferTime(this.videoBuffer);
			m_ns.play(ad.getFlvURL());
            //this.log(this + ".motifAdHolder.onConnect(): Streaming ad playing...\n");
        }
    }

    public function getAdId(Void):Number {
        return m_motifAdSWF.getAd().getAdId();
    }

/*
-------------------------------------------------------------------------------------------
	Original Versions of methods as referenced by documentation
	Motif Product Specialist has modified these in the uncommented versions
------------------------------------------------------------------------------------------

    public function onLoad(Void):Void {
        //Required. Change to host if outside US (e.g. uk.doubleclick.net)
        System.security.allowDomain(this.protocol + this.host);
		System.security.allowDomain("http://thstmd22.doubleclick.net"); //only needed in QA
		
        m_motifAdSWF = this.createEmptyMovieClip("motifAdSWF_mc", this.getNextHighestDepth());
		
		var adswf = (flashPlayer == 7) ? adswfPlayer7 : adswfPlayer8;

        //This URL is the same for all clients. It is versioned and may be updated over time
        this.m_motifAdSWF.loadMovie(this.protocol + this.host + "/879366/" + adswf);
		//this.log("Loading " + (this.protocol + this.host + "/879366/" + adswf) +"\n");
        //this.log("AdHolder loaded\n");
    }


    // onDartShellLoaded method must be present and have the following signature
    // since it will be invoked by DartShell after it has successfully initialized
    public function onDartShellLoaded(Void):Void {
        //this.log("Dart Shell Loaded\n");
        // initialize reference
        m_motifAd = m_motifAdSWF.instanceName;
				
		// Best practice is to either use loadAdAsset OR split between Flash and streaming handlers, not both.

		// m_motifAdSWF.addEventListener("onAdLoaded", this);
		m_motifAdSWF.addEventListener("onF2FAdLoaded", this);
        m_motifAdSWF.addEventListener("onInStreamAdLoaded", this);
        m_motifAdSWF.addEventListener("onError", this);

		// Alternative #1: Define callback functions directly
        // m_motifAdSWF.onInStreamAdLoaded = this.myFunction; 
		
		// Alternative #2: Define callback functions on object
		// listenObject = new Object();
        // listenObject.onError = function (errorObj:Object) {
        //    // do error handling here
        // };
        // m_motifAdSWF.addEventListener("onError", listenObject);		

        // The ad load in this example is immediate, it can be done in a more controlled manner if desired
     //    this.loadNewAd();
    }

    //user defined error handler, should be named onError
    public function onError(errorObj:Object) {
        //sent any errors to the custom error handler
        //this.log(errorObj.msg + "\n");
        //this.log(errorObj.shellError.getErrorType() + "\n");
        //this.log(errorObj.shellError.getErrorCode() + "\n");
        //this.log(errorObj.shellError.getErrorMessage()+ "\n");
		//_parent.onError();
		
    }
*/
}